package com.jewelry.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jewelry.entity.*;
import com.jewelry.mapper.AddressMapper;
import com.jewelry.mapper.OrderItemMapper;
import com.jewelry.mapper.OrderMapper;
import com.jewelry.service.OrderItemService;
import com.jewelry.service.OrderService;
import com.jewelry.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author LZL
 * @description 针对表【t_order】的数据库操作Service实现
 * @createDate 2024-03-21 20:53:04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderItemService orderItemService;

    @Resource
    private ProductService productService;

    @Override
    @Transactional
    public Order addOrder(Integer addressId, HttpSession session) {
        ValueOperations<String, Object> orderRedis = redisTemplate.opsForValue();
        // 1、先把订单放到数据库里面
        // 获取用户信息
        User user = (User) session.getAttribute("user");
        // 获取地址信息
        Address address = addressMapper.selectById(addressId);
        // 获取购物车
        Cart cart = (Cart) orderRedis.get("cart:" + user.getUserId());
        Order order = new Order();
        BeanUtils.copyProperties(address, order);
        order.setUserName(address.getName());
        order.setTotalMoney(cart.getTotalMoney());
        order.setStatus("未支付");
        long orderId = IdUtil.getSnowflake(1, 1).nextId();
        order.setOrderId(orderId);
        order.setCreateDate(new Date());
        // 添加订单
        orderMapper.insert(order);
        // 2、把订单项放到数据库里
        LinkedHashMap<Integer, CartItem> items = cart.getItems();
        Set<Integer> keySet = items.keySet();
        Map map = new HashMap();
        for (CartItem cartItem : items.values()) {
            if (cartItem.isChecked()) {

                map.put(cartItem.getProductId(), cartItem.getCount());
                // 减少库存
                productService.lambdaUpdate()
                        .set(Product::getStock, productService.getById(cartItem.getProductId()).getStock() - cartItem.getCount())
                        .eq(Product::getProductId, cartItem.getProductId())
                        .update();
                // 修改商品销量
                productService.lambdaUpdate()
                        .set(Product::getSale, productService.getById(cartItem.getProductId()).getSale() + cartItem.getCount())
                        .eq(Product::getProductId, cartItem.getProductId())
                        .update();
            }
        }
        orderItemMapper.insertOrderItem(map, orderId);
        // 3、将购物车清空
        // redisTemplate.delete("cart:"+user.getUserId());
        // 删除勾选的购物车项
        LinkedHashMap<Integer, CartItem> newCartItems = new LinkedHashMap<>();
        for (Integer productId : items.keySet()) {
            if (!items.get(productId).isChecked()) {
                newCartItems.put(productId, items.get(productId));
            }
        }
        cart.setItems(newCartItems);
        // 更新redis中的购物车
        orderRedis.set("cart:" + user.getUserId(), cart);

        // Iterator<Map.Entry<Integer, CartItem>> iterator = items.entrySet().iterator();
        // while (iterator.hasNext()) {
        //     Map.Entry<Integer, CartItem> entry = iterator.next();
        //     CartItem cartItem = entry.getValue();
        //
        //     if (cartItem.isChecked()) {
        //         iterator.remove(); // 使用迭代器的remove()方法删除元素
        //     }
        // }

        return order;
    }

    @Override
    public void deleteOrder(Long orderId) {
        System.err.println("orderId = " + orderId);
        // 获取订单项
        for (OrderItem orderItem : orderItemService.lambdaQuery().eq(OrderItem::getOrderId, orderId).list()) {
            // 修改库存
            productService.lambdaUpdate()
                    .set(Product::getStock, productService.getById(orderItem.getProductId()).getStock() + orderItem.getCount())
                    .eq(Product::getProductId, orderItem.getProductId())
                    .update();
            // 减少销量
            productService.lambdaUpdate()
                    .set(Product::getSale, productService.getById(orderItem.getProductId()).getSale() - orderItem.getCount())
                    .eq(Product::getProductId, orderItem.getProductId())
                    .update();
        }

        // 删除订单项;
        orderItemMapper.delete(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderId));
        // 删除订单
        orderMapper.deleteById(orderId);
    }

    @Override
    public String updateOrderStatus(Long orderId, String status) {
//        if (status.equals("待收货")) {
//            List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderId));
//            orderItems.forEach(orderItem -> {
//                productService.lambdaUpdate().eq(Product::getProductId,orderItem.getProductId())
//                        .setSql("stock = stock - " + orderItem.getCount()).update();
//            }
//        }
        Order order = orderMapper.selectById(orderId);
        if (status.equals("待收货")) {  // 点击发货
            if (order.getStatus().equals("待收货")) {
                return "Shipped";
            } else if (order.getStatus().equals("待评价")) {
                return "Shipped";
            } else if (order.getStatus().equals("未支付")) {
                return "Unpaid";
            }
        }
        if (status.equals("待评价")) {  // 点击确认收货
            if (order.getStatus().equals("未支付")) {
                return "Unpaid";
            } else if (order.getStatus().equals("待发货")) {
                return "Not-arrived";
            } else if (order.getStatus().equals("待评价")) {
                return "Received-goods";
            }
        }
        System.out.println("order.getStatus() = " + order.getStatus());
        System.out.println("status = " + status);
        orderMapper.updateOrderStatus(orderId, status);
        return "success";
    }

    @Override
    public Page<Order> selectOrder(Long orderId, String userName, Integer pageNum, Integer pageSize, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Integer role = user.getRole();
        Integer userId = user.getUserId();
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        if (role == 1) {
            wrapper.eq("user_id", userId);
        }
        if (userName != null) {
            wrapper.like("user_name", userName);
        }
        Page<Order> page = new Page<>(pageNum, pageSize);
        Page<Order> orders = orderMapper.selectPage(page, wrapper);
        return orders;
    }
}




